package com.runen.infinitemovement.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.MemberListAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.CompanyAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.MemberEntity;
import com.runen.infinitemovement.model.entity.PictrueEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.UiUtil;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.AddCorpsPoppupWindow;
import com.runen.infinitemovement.widget.popupwind.CommonDialog;
import com.runen.infinitemovement.widget.popupwind.HandOverTeamPoppupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.PermissionUtils;
import com.runen.rxnetlibrary.utils.TimeUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.runen.rxnetlibrary.utils.constant.PermissionConstants;
import com.runen.rxnetlibrary.utils.helper.DialogHelper;
import com.zhihu.matisse.Matisse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyTeamActivity extends BaseActivity {
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.top_tv_right)
    TextView topTvRight;
    @BindView(R.id.rv_member_list)
    RecyclerView rvMemberList;
    @BindView(R.id.rci_team_logo)
    RoundedCornersImage rciTeamLogo;
    @BindView(R.id.tv_team_name)
    TextView tvTeamName;
    @BindView(R.id.tv_my_team_number)
    TextView tvMyTeamNumber;
    @BindView(R.id.tv_change_team)
    TextView tvChangeTeam;
    @BindView(R.id.rci_captain_header)
    RoundedCornersImage rciCaptainHeader;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_hozom_num)
    TextView tvHozomNum;
    @BindView(R.id.tv_member_num)
    TextView tvMemberNum;
    @BindView(R.id.ll_leader)
    LinearLayout llLeader;
    @BindView(R.id.tv_leader)
    TextView tvLeader;
    private MemberListAdapter memberListAdapter;
    private HandOverTeamPoppupWindow poppupWindow;
    private String leaderId = "";
    private String companyId;
    private String parentId;
    private String logo;
    private List<Uri> avatar = new ArrayList<>();
    private int REQUEST_CODE_CHOOSE = 23;
    private String targetId = "";
    private boolean isTeamGroup;//是否是军团

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_team;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        targetId = getIntent().getStringExtra("targetId");
        isTeamGroup = getIntent().getBooleanExtra(ActivityCompat.TeamGroup, false);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvMemberList.setLayoutManager(layoutManager);
        memberListAdapter = new MemberListAdapter(this);
        rvMemberList.setAdapter(memberListAdapter);
        if (!TextUtils.isEmpty(targetId)) {
            topTvRight.setVisibility(View.INVISIBLE);
            tvChangeTeam.setVisibility(View.GONE);
            rciTeamLogo.setEnabled(false);
//            tvTeamName.setCompoundDrawables(null, null, null, null);
        } else {
            topTvRight.setVisibility(View.VISIBLE);
            tvChangeTeam.setVisibility(View.VISIBLE);
            rciTeamLogo.setEnabled(true);
//            tvTeamName.setCompoundDrawables(null, null, CommonUtil.getDrawable(R.mipmap.ico_editing), null);
            targetId = "";
        }


    }

    private String myTeamNumber = "我的队伍：%s人";
    private String myTeamNumber1 = "当前队伍：%s人";
    private String memberNumber = "成员（%s）";
    private String createTime = "创建时间：%s";
    private String companyName;
    private boolean isInvite;
    private boolean isHeader;

    @Override
    protected void onResume() {
        super.onResume();
        if (!isHeader) {
            initData();
        }
    }

    private void initData() {
        showDialog();
        String targetIdCompany = "?targetId=%s";
        new CompanyAPI().getMemberList(String.format(targetIdCompany, targetId), new BaseResultCallback<MemberEntity>() {
            @Override
            public void onResponse(MemberEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (response.data != null) {
                        if (isTeamGroup) {
                            tvMyTeamNumber.setText(String.format(myTeamNumber1, response.data.memberCount));
                        } else {
                            tvMyTeamNumber.setText(String.format(myTeamNumber, response.data.memberCount));
                        }
                        if (response.data.team != null) {
                            logo = response.data.team.logo;
                            if (TextUtils.isEmpty(logo)) {
                                GlideUtils.loadImage(MyTeamActivity.this, R.mipmap.ico_person_head, rciTeamLogo);
                            } else {
                                GlideUtils.loadImage(MyTeamActivity.this, logo, rciTeamLogo);
                            }
                            tvTeamName.setText(response.data.team.companyName);
                            companyName = response.data.team.companyName;
                            companyId = response.data.team.companyId;
                            parentId = response.data.team.parentId;

                        }
                        if (response.data.leader != null) {
                            tvLeader.setVisibility(View.VISIBLE);
                            llLeader.setVisibility(View.VISIBLE);
                            if (TextUtils.isEmpty(response.data.leader.headImgUrl)) {
                                GlideUtils.loadImage(MyTeamActivity.this, R.mipmap.ico_person_head, rciCaptainHeader);
                            } else {
                                GlideUtils.loadImage(MyTeamActivity.this, response.data.leader.headImgUrl, rciCaptainHeader);
                            }
                            tvMemberName.setText(response.data.leader.nickname);
                            tvTime.setText(String.format(createTime, TimeUtil.dealDateFormat2(response.data.leader.createTime)));
                            tvHozomNum.setText(response.data.leader.tinder + "颗");
                            tvMemberNum.setText(String.format(memberNumber, (response.data.memberCount - 1)));
                            leaderId = response.data.leader.userId;
                            if (!TextUtils.isEmpty(leaderId) && leaderId.equals(UserAPI.getUserId())) {
                                tvTeamName.setCompoundDrawablesWithIntrinsicBounds(null, null, CommonUtil.getDrawable(R.mipmap.ico_editing), null);
                            } else
                                tvTeamName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                        } else {
                            tvLeader.setVisibility(View.GONE);
                            llLeader.setVisibility(View.GONE);
                            tvMemberNum.setText(String.format(memberNumber, (response.data.memberCount)));
                        }
                        if (response.data.teamMemberList != null) {
                            if (response.data.teamMemberList.size() > 0) {
                                memberListAdapter.setNewInstance(response.data.teamMemberList);
                                memberListAdapter.notifyDataSetChanged();
                                poppupWindow = HandOverTeamPoppupWindow.getInstance(MyTeamActivity.this, response.data.teamMemberList);
                            } else {
                                isInvite = true;
//                                tvChangeTeam.setText("邀请好友");
                            }
                        }

                        if (isTeamGroup) {
                            topTitle.setText("团队");
                            topTvRight.setVisibility(View.INVISIBLE);
                            tvChangeTeam.setVisibility(View.GONE);
                            tvTeamName.setCompoundDrawablesWithIntrinsicBounds(null, null,
                                    CommonUtil.getDrawable(R.mipmap.ico_editing), null);
                            rciTeamLogo.setEnabled(true);
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });
    }


    @OnClick({R.id.top_btn_left, R.id.top_tv_right, R.id.tv_change_team, R.id.tv_team_name, R.id.rci_team_logo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.top_tv_right:
                Intent intent = new Intent(this, InviteFriendsActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_change_team:
                if (!TextUtils.isEmpty(leaderId) && leaderId.equals(UserAPI.getUserId()) && !isInvite) {
                    showPopup();
                } else {
//                    if (isInvite) {
//                        Intent intent2 = new Intent(this, InviteFriendsActivity.class);
//                        startActivity(intent2);
//                    } else {
                    Intent intent1 = new Intent(MyTeamActivity.this, CheckTeamActivity.class);
                    intent1.putExtra("companyId", parentId);
                    intent1.putExtra("type", 1);
                    startActivity(intent1);
//                    }
                }

                break;
            case R.id.tv_team_name:
                if ((!TextUtils.isEmpty(leaderId) && leaderId.equals(UserAPI.getUserId())) || isTeamGroup) {
                    showPupop();
                }
                break;
            case R.id.rci_team_logo:
                if ((!TextUtils.isEmpty(leaderId) && leaderId.equals(UserAPI.getUserId())) || isTeamGroup) {
                    isHeader = true;
                    onPermission();
                }
                break;
        }
    }

    /**
     * 获取拍照权限
     */
    private void requestCamera() {
        UiUtil.getImageSelectorConfig(this, REQUEST_CODE_CHOOSE);
    }

    @SuppressLint("WrongConstant")
    private void onPermission() {
        //请求动态权限
        PermissionUtils.permission(
                PermissionConstants.STORAGE,
                PermissionConstants.CAMERA,
                PermissionConstants.WRITE_EXTERNAL_STORAGE,
                PermissionConstants.ACCESS_COARSE_LOCATION)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(final ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        requestCamera();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            DialogHelper.showOpenAppSettingDialog();
                        }
                    }
                })
                .request();
    }

    private void showPopup() {
        String usInfo = "确定选择 %s 为新队长，你将自动放弃群主身份。";
        if (poppupWindow != null) {
            poppupWindow.show();
            poppupWindow.setOnHandOverListener(new HandOverTeamPoppupWindow.OnHandOverListener() {
                @Override
                public void onHandOver(String userId, String userName) {
                    CommonDialog.getInstance(MyTeamActivity.this, "", String.format(usInfo, userName), "取消", "确定", 0).setOnClickListener(new CommonDialog.OnClickListener() {
                        @Override
                        public void onSendListener() {

                        }

                        @Override
                        public void onDismiss() {
                            onSure(userId);
                        }
                    });
                }
            });
        }
    }

    private void onSure(String userId) {
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("teamName", companyName);
            object.put("leader", userId);
            object.put("teamId", companyId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new CompanyAPI().createOrEditingTeam(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    dismissDialog();
                    poppupWindow.dismiss();
                    Intent intent1 = new Intent(MyTeamActivity.this, CheckTeamActivity.class);
                    intent1.putExtra("companyId", parentId);
                    intent1.putExtra("type", 1);
                    startActivity(intent1);
                } else {
                    ToastUtils.showShort(response.getMessage());
                }

            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
        switch (event.getMsg()) {
            case 102:
                initData();
                break;
            default:
                break;
        }
    }

    AddCorpsPoppupWindow addCorpsPoppupWindow;

    private void showPupop() {
        addCorpsPoppupWindow = AddCorpsPoppupWindow.getInstance(this, companyName);
        addCorpsPoppupWindow.setOnHozonClickListener(new AddCorpsPoppupWindow.OnHozonClickListener() {
            @Override
            public void onHozomClick(String corpsName) {
                companyName = corpsName;
                onAddCorps();
            }
        });
        addCorpsPoppupWindow.show();

    }

    private void onAddCorps() {
        showDialog();
        JSONObject object = new JSONObject();
        try {
            object.put("teamName", companyName);
            object.put("teamId", companyId);
            object.put("logo", logo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new CompanyAPI().createOrEditingTeam(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() == 0) {
                    dismissDialog();
                    tvTeamName.setText(companyName);
                    if (addCorpsPoppupWindow != null) {
                        addCorpsPoppupWindow.dismiss();
                    }
                    EventBus.getDefault().post(new EventBusEntity(EventBusEntity.CODE_106));
                } else {
                    ToastUtils.showShort(response.getMessage());
                }

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                avatar = Matisse.obtainResult(data);
                if (avatar != null && avatar.size() > 0) {
                    Log.e("OnActivityResult ", String.valueOf(avatar.get(0)));
                    GlideUtils.loadImage(MyTeamActivity.this, avatar.get(0).toString(), rciTeamLogo);
                    File file = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        file = CommonUtil.uriToFileApiQ(this, avatar.get(0));
                    } else {
                        file = CommonUtil.uri2File(this, avatar.get(0));
                    }
                    updateByImgUrl(file);
                }
            }
        }
    }

    private void updateByImgUrl(File imaUrl) {
        Log.e("OnActivityResult2 ", imaUrl.toString());
        TreeMap<String, String> mapType = new TreeMap<>();
        mapType.put("type", "headImg");
//        File file = ScreenShotHelper.compressImage2(CommonUtil.getImage(imaUrl.getPath()), this);
        TreeMap<String, File> mapFile = new TreeMap<>();
        mapFile.put("file", imaUrl);
        new UserAPI().putFile(mapType, mapFile, new BaseResultCallback<PictrueEntity>() {
            @Override
            public void onResponse(PictrueEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        Message message = new Message();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("headImgUrl", response.data.url);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String headUrl = bundle.getString("headImgUrl");
                    logo = headUrl;
                    onAddCorps();
                    break;
            }
        }
    };
}